<template>
  <view class="store-container">
    <!-- 搜索栏 -->
    <view class="search-section">
      <view class="custom-search-bar">
        <uni-icons type="search" size="18" color="#999" class="search-icon" />
        <input
            class="search-input"
            placeholder="搜索店铺名称/电话/地址"
            :value="searchValue"
            @input="onSearchInput"
            @confirm="onSearch"
            confirm-type="search"
        />
      </view>
    </view>

    <!-- 店铺列表 -->
    <view class="store-list-section">
      <uni-swipe-action>
        <uni-swipe-action-item
            v-for="(store, index) in filteredStores"
            :key="store.id"
            :right-options="swipeOptions"
            :auto-close="false"
            @click="onSwipeClick"
        >
          <uni-list-item
              :title="store.name"
              :note="store.address"
              :thumb="store.image || '/static/logo.png'"
              thumb-size="lg"
              :clickable="true"
              @click="onStoreClick(store)"
          >
            <template v-slot:footer>
              <view class="store-info-footer">
                <uni-icons type="location"><text class="store-distance">{{ store.distance }}km</text></uni-icons>
                <uni-icons type="phone"><text class="store-phone">{{ store.phone }}</text></uni-icons>
              </view>
            </template>
          </uni-list-item>
        </uni-swipe-action-item>
      </uni-swipe-action>

      <!-- 空状态提示 -->
      <view v-if="filteredStores.length === 0" class="empty-state">
        <uni-icons type="shop" size="60" color="#ccc" />
        <text class="empty-text">暂无店铺信息</text>
        <button class="add-button" @click="onAddStore">添加店铺</button>
      </view>
    </view>

    <!-- 添加店铺悬浮按钮 -->
    <uni-fab
        :pattern="fabPattern"
        :horizontal="'right'"
        :vertical="'bottom'"
        :direction="'horizontal'"
        @fabClick="onFabClick"
    />

    <!-- 操作菜单弹窗 -->
    <uni-popup ref="actionPopup" type="bottom">
      <view class="action-menu">
        <view class="menu-item" @click="onAddStore">
          <uni-icons type="plus" size="20" />
          <text>新增店铺</text>
        </view>
        <view class="menu-item" @click="onImportStore">
          <uni-icons type="upload" size="20" />
          <text>导入店铺</text>
        </view>
        <view class="menu-item" @click="onExportStore">
          <uni-icons type="download" size="20" />
          <text>导出店铺</text>
        </view>
        <view class="menu-item cancel" @click="closeActionMenu">
          <text>取消</text>
        </view>
      </view>
    </uni-popup>
    <!-- 新增店铺弹窗 -->
    <uni-popup ref="addPopup" type="center">
      <view class="add-store-popup">
        <view class="popup-header">
          <text class="popup-title">新增店铺</text>
          <uni-icons type="close" size="20" @click="closeAddPopup" />
        </view>

        <view class="popup-content">
          <uni-forms ref="addForm" :modelValue="newStore" :rules="storeRules">
            <uni-forms-item label="店铺编号" name="code" required>
              <uni-easyinput
                  v-model="newStore.code"
                  placeholder="请输入店铺编号"
                  :inputBorder="false"
              />
            </uni-forms-item>
            <uni-forms-item label="店铺名称" name="name" required>
              <uni-easyinput
                  v-model="newStore.name"
                  placeholder="请输入店铺名称"
                  :inputBorder="false"
              />
            </uni-forms-item>

            <uni-forms-item label="联系电话" name="phone" required>
              <uni-easyinput
                  v-model="newStore.phone"
                  placeholder="请输入联系电话"
                  type="number"
                  :inputBorder="false"
              />
            </uni-forms-item>

            <uni-forms-item label="店铺地址" name="address" required>
              <uni-easyinput
                  v-model="newStore.address"
                  placeholder="请输入店铺地址"
                  :inputBorder="false"
              />
            </uni-forms-item>

            <uni-forms-item label="距离(km)" name="distance">
              <uni-easyinput
                  v-model="newStore.distance"
                  placeholder="请输入距离"
                  type="number"
                  :inputBorder="false"
              />
            </uni-forms-item>

            <uni-forms-item label="店铺描述" name="description">
              <uni-easyinput
                  v-model="newStore.description"
                  placeholder="请输入店铺描述"
                  type="textarea"
                  :inputBorder="false"
              />
            </uni-forms-item>
          </uni-forms>
        </view>

        <view class="popup-footer">
          <button class="cancel-btn" @click="closeAddPopup">取消</button>
          <button class="confirm-btn" @click="saveStore">保存</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import {storeApi} from "@/api/store/store";

export default {
  data() {
    return {
      searchValue: '',
      stores: [
        {
          id: 1,
          name: '旗舰店',
          image: '/static/c1.png',
          phone: '13800138000',
          address: '北京市朝阳区建国路88号',
          distance: 1.2,
          description: '旗舰店拥有最全的商品种类和优质服务'
        },
        {
          id: 2,
          name: '分店一',
          image: '/static/c2.png',
          phone: '13900139000',
          address: '北京市海淀区中关村大街1号',
          distance: 3.5,
          description: '科技感十足的分店，主打智能产品'
        },
        {
          id: 3,
          name: '社区店',
          image: '/static/c3.png',
          phone: '13600136000',
          address: '北京市西城区西单北大街130号',
          distance: 0.8,
          description: '便民社区店，服务周边居民'
        }
      ],
      swipeOptions: [
        {
          text: '编辑',
          style: {
            backgroundColor: '#007AFF'
          }
        },
        {
          text: '删除',
          style: {
            backgroundColor: '#DD524D'
          }
        }
      ],
      fabPattern: {
        color: '#007AFF',
        backgroundColor: '#fff',
        selectedColor: '#007AFF',
        buttonColor: '#007AFF'
      },
      currentStore: null,
      newStore: {
        code:'',
        name: '',
        phone: '',
        address: '',
        distance: 0,
        description: '',
        image: '/static/logo.png',
        status: 1,
      },
      storeRules: {
        name: {
          rules: [{
            required: true,
            errorMessage: '请输入店铺名称'
          }]
        },
        phone: {
          rules: [{
            required: true,
            errorMessage: '请输入联系电话'
          }, {
            validateFunction: (rule, value, data, callback) => {
              if (!/^1[3-9]\d{9}$/.test(value)) {
                callback('请输入正确的手机号码格式')
              }
              return true
            }
          }]
        },
        address: {
          rules: [{
            required: true,
            errorMessage: '请输入店铺地址'
          }]
        }
      }
    }
  },
  computed: {
    filteredStores() {
      if (!this.searchValue) {
        return this.stores
      }
      const keyword = this.searchValue.toLowerCase()
      return this.stores.filter(store =>
          store.name.toLowerCase().includes(keyword) ||
          store.phone.includes(keyword) ||
          store.address.toLowerCase().includes(keyword)
      )
    }
  },
  onLoad() {
    this.loadStores()
  },
  methods: {
    // 加载店铺列表
    async loadStores() {
      try {
        uni.showLoading({ title: '加载中...' })
        const res = await storeApi.getStores()
        this.stores = res.data || []
      } catch (error) {
        console.error('获取店铺列表失败:', error)
        uni.showToast({ title: '获取店铺列表失败', icon: 'none' })
      } finally {
        uni.hideLoading()
      }
    },
    onSearch(e) {
      const value = e.detail.value || e.target.value;
      console.log('搜索店铺:', value);
      if (value.trim()) {
        // 这里可以添加搜索逻辑，或者保持原有的搜索行为
        const keyword = this.searchValue.toLowerCase()
        this.filteredStores = this.stores.filter(store =>
            store.name.toLowerCase().includes(keyword) ||
            store.phone.includes(keyword) ||
            store.address.toLowerCase().includes(keyword)
        )
      }
    },
    onSearchInput(e) {
      this.searchValue = e.detail.value || e.target.value;
      // 实时搜索
      const keyword = this.searchValue.toLowerCase()
      this.filteredStores = this.stores.filter(store =>
          store.name.toLowerCase().includes(keyword) ||
          store.phone.includes(keyword) ||
          store.address.toLowerCase().includes(keyword)
      )
    },
    onClearSearch() {
      this.searchValue = '';
      this.filteredStores = this.stores;
    },
    onStoreClick(store) {
      console.log('点击店铺:', store)
      uni.navigateTo({
        url: `/pages/store/detail/index?id=${store.id}`
      })
    },
    onSwipeClick(e) {
      const { content, index } = e
      const store = this.filteredStores[index]

      if (content.text === '编辑') {
        this.onEditStore(store)
      } else if (content.text === '删除') {
        this.onDeleteStore(store)
      }
    },
    onEditStore(store) {
      console.log('编辑店铺:', store)
      uni.navigateTo({
        url: `/pages/store/edit/index?id=${store.id}`
      })
    },
    onDeleteStore(store) {
      uni.showModal({
        title: '确认删除',
        content: `确定要删除店铺"${store.name}"吗？此操作不可恢复。`,
        success: (res) => {
          if (res.confirm) {
            this.stores = this.stores.filter(s => s.id !== store.id)
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            })
          }
        }
      })
    },
    onFabClick() {
      this.$refs.actionPopup.open()
    },
    onImportStore() {
      this.$refs.actionPopup.close()
      uni.showToast({
        title: '导入功能开发中',
        icon: 'none'
      })
    },
    onExportStore() {
      this.$refs.actionPopup.close()
      uni.showToast({
        title: '导出功能开发中',
        icon: 'none'
      })
    },
    closeActionMenu() {
      this.$refs.actionPopup.close()
    },
    onAddStore() {
      this.$refs.actionPopup.close()
      this.resetNewStore()
      this.$refs.addPopup.open()
    },

    closeAddPopup() {
      this.$refs.addPopup.close()
    },

    saveStore() {
      this.$refs.addForm.validate().then(res => {
        const newStore = {
          ...this.newStore,
          distance: parseFloat(this.newStore.distance) || 0
        }
        storeApi.createStore(newStore)
        uni.showToast({
          title: '新增成功',
          icon: 'success'
        })
        this.closeAddPopup()
      }).catch(err => {
        console.log('表单验证失败:', err)
      })
    },

    resetNewStore() {
      this.newStore = {
        code:'',
        name: '',
        phone: '',
        address: '',
        distance: 0,
        description: '',
        image: '/static/logo.png',
        status: 1,
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.store-container {
  padding: 0;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.search-section {
  padding: 10px 15px;
  background-color: #ffffff;
  position: sticky;
  top: 0;
  z-index: 100;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.1);
}

.custom-search-bar {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 20px;
  padding: 8px 16px;
  height: 36px;
}

.search-icon {
  margin-right: 8px;
  flex-shrink: 0;
}

.search-input {
  flex: 1;
  height: 100%;
  font-size: 14px;
  color: #333;
  background: transparent;
  border: none;
  outline: none;

  &::placeholder {
    color: #999;
    font-size: 14px;
  }
}


.store-list-section {
  padding: 0;
}

.store-info-footer {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

.store-distance {
  font-size: 14px;
  color: #007AFF;
  font-weight: 500;
}

.store-phone {
  font-size: 12px;
  color: #999;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-text {
  margin: 20px 0;
  color: #999;
  font-size: 16px;
}

.add-button {
  background-color: #007AFF;
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 12px 24px;
  font-size: 14px;
}

.action-menu {
  background-color: #fff;
  border-radius: 16px 16px 0 0;
  padding: 20px;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  font-size: 16px;

  &:active {
    background-color: #f5f5f5;
  }

  &:last-child {
    border-bottom: none;
  }

  &.cancel {
    justify-content: center;
    color: #999;
    font-weight: 500;
  }
}

// 优化滑动操作样式
::v-deep .uni-swipe_button {
  min-width: 80px;
  justify-content: center;
}

::v-deep .uni-list-item__container {
  padding: 16px 15px;
}

::v-deep .uni-list-item__content {
  padding-right: 12px;
}

.add-store-popup {
  background-color: #fff;
  border-radius: 12px;
  width: 85vw;
  max-height: 80vh;
  overflow: hidden;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 20px 15px;
  border-bottom: 1px solid #f0f0f0;
}

.popup-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.popup-content {
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
}

.popup-footer {
  display: flex;
  padding: 15px 20px 20px;
  border-top: 1px solid #f0f0f0;
  gap: 12px;
}

.cancel-btn {
  flex: 1;
  background-color: #f8f8f8;
  color: #333;
  border: none;
  border-radius: 8px;
  padding: 12px;
  font-size: 14px;
}

.confirm-btn {
  flex: 1;
  background-color: #007AFF;
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 12px;
  font-size: 14px;
}

::v-deep .uni-forms-item__label {
  width: 80px !important;
}

::v-deep .uni-easyinput__content {
  border: 1px solid #e5e5e5 !important;
  border-radius: 6px !important;
}
</style>